import React, { useState, useEffect } from 'react';
import { Elements, PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { stripeService } from '../services/stripe';
import { useLanguage } from '../contexts/LanguageContext';

interface StripeCheckoutFormProps {
  clientSecret: string;
  amount: number;
  billingDetails: {
    name: string;
    email: string;
    address: string;
    postalCode: string;
    country: string;
  };
  onSuccess: () => void;
  onCancel: () => void;
}

const StripeCheckoutForm = ({ 
  clientSecret, 
  amount, 
  billingDetails,
  onSuccess, 
  onCancel 
}: StripeCheckoutFormProps) => {
  const stripe = useStripe();
  const elements = useElements();
  const { language } = useLanguage();
  const [isProcessing, setIsProcessing] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string>('');

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    setIsProcessing(true);
    setErrorMessage('');

    try {
      const result = await stripeService.confirmPayment(
        stripe,
        elements,
        clientSecret,
        {
          name: billingDetails.name,
          email: billingDetails.email,
          address: {
            line1: billingDetails.address,
            postal_code: billingDetails.postalCode,
            country: billingDetails.country,
          },
        }
      );

      if (result.success) {
        onSuccess();
      } else {
        const errorMsg = typeof result.error === 'string' ? result.error : (language === 'zh-CN' ? '支付失败，请重试' : 'Payment failed, please try again');
        setErrorMessage(errorMsg);
      }
    } catch (error) {
      console.error('Payment error:', error);
      setErrorMessage(language === 'zh-CN' ? '支付处理失败' : 'Payment processing failed');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="bg-gray-50 dark:bg-gray-900 p-4 rounded-lg">
        <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
          {language === 'zh-CN' ? '支付金额：' : 'Total Amount: '}
          <span className="font-bold text-xl text-gray-900 dark:text-white">
            ${amount.toFixed(2)}
          </span>
        </p>
      </div>

      <div className="border border-gray-300 dark:border-gray-600 rounded-lg p-4 bg-white dark:bg-gray-800">
        <PaymentElement 
          options={{
            layout: 'tabs',
            paymentMethodOrder: ['card', 'wechat_pay', 'alipay', 'customer_balance', 'us_bank_account'],
          }}
        />
      </div>

      {errorMessage && (
        <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
          <p className="text-sm text-red-600 dark:text-red-400">{errorMessage}</p>
        </div>
      )}

      <div className="flex space-x-3">
        <button
          type="button"
          onClick={onCancel}
          disabled={isProcessing}
          className="flex-1 px-6 py-3 border-2 border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed font-medium"
        >
          {language === 'zh-CN' ? '取消' : 'Cancel'}
        </button>
        <button
          type="submit"
          disabled={isProcessing || !stripe || !elements}
          className="flex-1 px-6 py-3 bg-gradient-to-r from-[#00d4ff] to-[#0f1c3f] text-white rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50 disabled:cursor-not-allowed font-medium"
        >
          {isProcessing 
            ? (language === 'zh-CN' ? '处理中...' : 'Processing...') 
            : (language === 'zh-CN' ? `支付 $${amount.toFixed(2)}` : `Pay $${amount.toFixed(2)}`)}
        </button>
      </div>
    </form>
  );
};

interface StripeCheckoutProps {
  isOpen: boolean;
  amount: number;
  billingDetails: {
    fullName: string;
    email: string;
    address: string;
    postalCode: string;
    country: string;
  };
  onSuccess: () => void;
  onClose: () => void;
}

export const StripeCheckout = ({ 
  isOpen, 
  amount, 
  billingDetails,
  onSuccess, 
  onClose 
}: StripeCheckoutProps) => {
  const { language } = useLanguage();
  const [clientSecret, setClientSecret] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [stripePromise, setStripePromise] = useState<any>(null);
  const [error, setError] = useState<string>('');
  
  // Detect dark mode
  const isDarkMode = document.documentElement.classList.contains('dark');

  useEffect(() => {
    // Load Stripe
    const loadStripeInstance = async () => {
      const stripe = await stripeService.getStripe();
      setStripePromise(stripe);
    };
    loadStripeInstance();
  }, []);

  useEffect(() => {
    if (isOpen && !clientSecret) {
      createPaymentIntent();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

  const createPaymentIntent = async () => {
    setIsLoading(true);
    setError('');
    try {
      const result = await stripeService.createPaymentIntent(amount);
      if (result.success && result.clientSecret) {
        setClientSecret(result.clientSecret);
      } else {
        // Show detailed error message
        const errorMsg = result.error instanceof Error 
          ? result.error.message 
          : (language === 'zh-CN' ? '创建支付会话失败' : 'Failed to create payment session');
        console.error('Payment intent creation failed:', result.error);
        setError(errorMsg);
      }
    } catch (error) {
      console.error('Failed to create payment intent:', error);
      const errorMsg = error instanceof Error 
        ? error.message 
        : (language === 'zh-CN' ? '创建支付会话失败' : 'Failed to create payment session');
      setError(errorMsg);
    } finally {
      setIsLoading(false);
    }
  };

  const handleClose = () => {
    setClientSecret(null);
    setError('');
    onClose();
  };

  const handleSuccess = () => {
    setClientSecret(null);
    setError('');
    onSuccess();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full p-6 max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center mb-6">
          <h3 className="text-2xl font-bold text-gray-900 dark:text-white">
            {language === 'zh-CN' ? 'Stripe 安全支付' : 'Stripe Secure Payment'}
          </h3>
          <button
            onClick={handleClose}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        {error && (
          <div className="mb-4 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
            <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
          </div>
        )}

        {isLoading ? (
          <div className="flex items-center justify-center py-16">
            <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-[#00d4ff]"></div>
          </div>
        ) : clientSecret && stripePromise ? (
          <Elements
            stripe={stripePromise}
            options={{
              clientSecret,
              locale: language === 'zh-CN' ? 'zh' : 'en',
              appearance: {
                theme: isDarkMode ? 'night' : 'stripe',
                variables: {
                  colorPrimary: '#00d4ff',
                  colorBackground: isDarkMode ? '#1f2937' : '#ffffff',
                  colorText: isDarkMode ? '#f3f4f6' : '#1f2937',
                  colorDanger: '#ef4444',
                  fontFamily: 'system-ui, sans-serif',
                  spacingUnit: '4px',
                  borderRadius: '8px',
                },
                rules: {
                  '.Tab': {
                    backgroundColor: isDarkMode ? '#374151' : '#f9fafb',
                    border: `1px solid ${isDarkMode ? '#4b5563' : '#e5e7eb'}`,
                    color: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.Tab:hover': {
                    backgroundColor: isDarkMode ? '#4b5563' : '#f3f4f6',
                  },
                  '.Tab--selected': {
                    backgroundColor: isDarkMode ? '#1f2937' : '#ffffff',
                    borderColor: '#00d4ff',
                    color: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.TabIcon': {
                    fill: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.TabIcon--selected': {
                    fill: '#00d4ff',
                  },
                  '.Input': {
                    backgroundColor: isDarkMode ? '#374151' : '#ffffff',
                    border: `1px solid ${isDarkMode ? '#4b5563' : '#d1d5db'}`,
                    color: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.Input:focus': {
                    borderColor: '#00d4ff',
                    boxShadow: `0 0 0 1px #00d4ff`,
                  },
                  '.Label': {
                    color: isDarkMode ? '#d1d5db' : '#6b7280',
                  },
                  '.Text': {
                    color: isDarkMode ? '#f3f4f6' : '#1f2937',
                  },
                  '.Error': {
                    color: '#ef4444',
                  },
                  // Card brand icons styling for dark mode
                  '.p-CardBrandIcon': {
                    opacity: isDarkMode ? '0.9' : '1',
                    filter: isDarkMode ? 'brightness(1.2) contrast(0.9)' : 'none',
                  },
                  '.p-CardBrandIcon--selected': {
                    opacity: '1',
                    filter: 'none',
                  },
                },
              },
            }}
          >
            <StripeCheckoutForm
              clientSecret={clientSecret}
              amount={amount}
              billingDetails={{
                name: billingDetails.fullName,
                email: billingDetails.email,
                address: billingDetails.address,
                postalCode: billingDetails.postalCode,
                country: billingDetails.country,
              }}
              onSuccess={handleSuccess}
              onCancel={handleClose}
            />
          </Elements>
        ) : (
          <div className="text-center py-16">
            <p className="text-gray-600 dark:text-gray-400">
              {language === 'zh-CN' ? '加载支付表单...' : 'Loading payment form...'}
            </p>
          </div>
        )}
      </div>
    </div>
  );
};
